import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { type ComplianceItem, type Attachment, ComplianceType } from '@/types/work';
import { 
  fetchComplianceItems, 
  addComplianceItem, 
  updateComplianceItem, 
  deleteComplianceItem,
  uploadAttachment,
  deleteAttachment
} from '@/api/work';
import {
  getRiskRelations,
  createRiskRelation,
  deleteRiskRelation,
  updateRiskRelations
} from '@/api/riskAssurance';


// 缓存有效期为5分钟
const CACHE_EXPIRY = 5 * 60 * 1000;


interface ComplianceState {
  // 状态
  items: ComplianceItem[];
  
  // 操作方法
  fetchItems: (assessment_plan_id?: string) => Promise<void>;
  addItem: (item: Omit<ComplianceItem, 'id' | 'updated_at'>) => Promise<void>;
  updateItem: (id: string, updates: Partial<ComplianceItem>) => Promise<void>;
  deleteItem: (id: string) => Promise<void>;
  uploadFile: (complianceItemId: string, file: File) => Promise<Attachment>;
  removeFile: (attachmentId: string) => Promise<void>;
  updateItemAttachments: (complianceItemId: string, attachments: Attachment[]) => void;
  
  // 风险关联方法
  updateRiskAssociations: (riskId: string, guaranteeIds: string[]) => Promise<void>;
  addAssociation: (riskId: string, guaranteeId: string) => Promise<void>;
  removeAssociation: (riskId: string, guaranteeId: string) => Promise<void>;
  
  // 派生状态
  getRiskItems: () => ComplianceItem[];
  getGuaranteeItems: () => ComplianceItem[];
  getSelectedBusinessId: () => string | null;
}


export const useComplianceStore = create<ComplianceState>()(
  devtools(
    (set, get) => {
      // 使用闭包来存储缓存
      const cache: Record<string, { items: ComplianceItem[]; timestamp: number }> = {};
      
      // 检查缓存是否有效
      const isCacheValid = (planId: string) => {
        const cached = cache[planId];
        if (!cached) return false;
        return Date.now() - cached.timestamp < CACHE_EXPIRY;
      };
      
      // 更新缓存
      const updateCache = (planId: string, items: ComplianceItem[]) => {
        cache[planId] = {
          items,
          timestamp: Date.now()
        };
      };

      return {
        // 初始状态
        items: [],
        
        // 获取所有检查项
        fetchItems: async (assessment_plan_id?: string) => {
          if (!assessment_plan_id) return;
          
          // 检查缓存是否有效
          if (isCacheValid(assessment_plan_id)) {
            set({ items: cache[assessment_plan_id].items });
            return;
          }

          try {
            const params = { assessment_plan_id };
            const items = await fetchComplianceItems(params);
            for (const item of items) {
              item.plan_id = assessment_plan_id;
            }     
            // 更新缓存
            updateCache(assessment_plan_id, items);
            
            set({ items });
          } catch (error) {
            console.error('Failed to fetch compliance items:', error);
            // 如果请求失败但有缓存，使用缓存
            if (cache[assessment_plan_id]) {
              set({ items: cache[assessment_plan_id].items });
            }
            throw error;
          }
        },
  
        // 添加检查项
        addItem: async (itemData) => {
          const newItem = await addComplianceItem({
            ...itemData,
            id: crypto.randomUUID(),
            updated_at: new Date().toISOString(),
          });
          
          // 更新缓存
          const assessment_plan_id = itemData.plan_id;
          if (assessment_plan_id && cache[assessment_plan_id]) {
            updateCache(assessment_plan_id, [...cache[assessment_plan_id].items, newItem]);
          }
          
          set(state => ({ items: [...state.items, newItem] }));
          return newItem;
        },
  
        // 更新检查项
        updateItem: async (id, updates) => {
          const item = get().items.find(item => item.id === id);
          if (!item) return;
          
          const updatedItem = await updateComplianceItem({
            ...item,
            ...updates,
            updated_at: new Date().toISOString(),
          });
          
          // 更新缓存
          const assessment_plan_id = item.plan_id;
          if (assessment_plan_id && cache[assessment_plan_id]) {
            const updatedItems = cache[assessment_plan_id].items.map(item => 
              item.id === id ? updatedItem : item
            );
            updateCache(assessment_plan_id, updatedItems);
          }
          
          set(state => ({
            items: state.items.map(item => 
              item.id === id ? updatedItem : item
            )
          }));
          
          return updatedItem;
        },
  
        // 删除检查项
        deleteItem: async (id) => {
          const item = get().items.find(item => item.id === id);
          if (!item) return;
          
          await deleteComplianceItem(id);
          
          // 更新缓存
          const assessment_plan_id = item.plan_id;
          if (assessment_plan_id && cache[assessment_plan_id]) {
            const updatedItems = cache[assessment_plan_id].items.filter(item => item.id !== id);
            updateCache(assessment_plan_id, updatedItems);
          }
          
          set(state => ({
            items: state.items.filter(item => item.id !== id)
          }));
          
          return true;
        },
  
        // 上传附件（只负责上传，不更新 store）
        uploadFile: async (complianceItemId, file) => {
    const attachment = await uploadAttachment(complianceItemId, file);
    return attachment;
  },
  
        // 删除附件（只负责删除，不更新 store）
        removeFile: async (attachmentId) => {
    await deleteAttachment(attachmentId);
  },
  
        // 更新指定检查项的附件列表（统一的附件更新方法）
        updateItemAttachments: (complianceItemId, attachments) => {
    set(state => ({
      items: state.items.map(item => 
        item.id === complianceItemId
          ? { 
              ...item, 
              attachments: attachments 
            }
          : item
      )
    }));
  },
  
        // 更新风险项的保障关联
        updateRiskAssociations: async (riskId, guaranteeIds) => {
    const riskItem = get().items.find(item => item.id === riskId);
    if (!riskItem) return;
    
    try {
      // 调用API更新关联关系
      await updateRiskRelations(riskId, guaranteeIds);
      
      // 更新本地状态
      set(state => ({
        items: state.items.map(item => 
          item.id === riskId 
            ? { ...item, related_guarantees: guaranteeIds, updated_at: new Date().toISOString() }
            : item
        )
      }));
    } catch (error) {
      console.error('Failed to update risk associations:', error);
      throw error;
    }
  },
  
        // 添加单个关联
        addAssociation: async (riskId, guaranteeId) => {
    const riskItem = get().items.find(item => item.id === riskId);
    if (!riskItem) return;
    
    const currentGuarantees = riskItem.related_guarantees || [];
    if (currentGuarantees.includes(guaranteeId)) return;
    
    try {
      // 调用API创建关联关系
      await createRiskRelation(riskId, guaranteeId);
      
      // 更新本地状态
      set(state => ({
        items: state.items.map(item => 
          item.id === riskId 
            ? { 
                ...item, 
                related_guarantees: [...currentGuarantees, guaranteeId], 
                updated_at: new Date().toISOString() 
              }
            : item
        )
      }));
    } catch (error) {
      console.error('Failed to add association:', error);
      throw error;
    }
  },
  
        // 移除单个关联
        removeAssociation: async (riskId, guaranteeId) => {
    const riskItem = get().items.find(item => item.id === riskId);
    if (!riskItem?.related_guarantees) return;
    
    try {
      // 获取关联关系
      const relations = await getRiskRelations(riskId);
      const relationToDelete = relations.find(r => r.guarantee_item_id === guaranteeId);
      
      if (relationToDelete) {
        // 调用API删除关联关系
        await deleteRiskRelation(relationToDelete.id);
        
        // 更新本地状态
        set(state => ({
          items: state.items.map(item => 
            item.id === riskId 
              ? { 
                  ...item, 
                  related_guarantees: item.related_guarantees?.filter(id => id !== guaranteeId) || [], 
                  updated_at: new Date().toISOString() 
                }
              : item
          )
        }));
      }
    } catch (error) {
      console.error('Failed to remove association:', error);
      throw error;
    }
  },
  
        // 获取所有风险项
        getRiskItems: () => {
          return get().items.filter(item => item.compliance_type === ComplianceType.RISK);
        },
        
        // 获取所有保障项
        getGuaranteeItems: () => {
          return get().items.filter(item => item.compliance_type === ComplianceType.GUARANTEE);
        },
        
        // 获取当前选中的业务ID
        getSelectedBusinessId: () => {
          // 从items中获取plan_id，假设所有items都属于同一个plan
          const items = get().items;
          if (items.length > 0 && items[0].plan_id) {
            return items[0].plan_id;
          }
          return null;
        }
      };
    }
  )
);
